package top.wardyan.wbaseswt.control.wtable;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;

import com.jfinal.aop.Aop;
import com.jfinal.plugin.activerecord.IRow;

//import top.wardyan.base.common.db.model.base.BaseModel;
//import top.wardyan.base.common.db.service.IBaseService;
//import top.wardyan.base.db.service.IMasterService;
import top.wardyan.wbaseswt.conf.Const;
import top.wardyan.wbaseswt.conf.model.SysDic;
import top.wardyan.wbaseswt.conf.model.SysTableCol;
import top.wardyan.wbaseswt.conf.service.ISysDicService;
import top.wardyan.wbaseswt.conf.service.ISysTableColService;
import top.wardyan.wbaseswt.control.WMenu;
import top.wardyan.wbaseswt.control.WMenuItem;
import top.wardyan.wbaseswt.util.Msg;

public class WTable extends Table{

	protected WTable self;
	protected List<? extends IRow<?>> datas;
	protected String tablename;
	protected boolean isAutoPack;
	private int type;	// 类型 1主表, 2明细表, 3非主明细表
	//private IBaseService<? extends BaseModel<?>> service;
	private ISysDicService dicService = Aop.get(ISysDicService.class);
	
	private ISysTableColService tableColService = Aop.get(ISysTableColService.class);
	
	public static final List<String> SKIPFIELDS = new ArrayList<>() {{
		this.add("sID");
		this.add("mID");
		this.add("dID");
		this.add("rAuthor_ID");
		this.add("rChecker_ID");
		this.add("rMender_ID");
		this.add("rAuditor_ID");
	}};
	
	public WTable(Composite parent, int style, String tablename) {
		// super(parent, style | SWT.VIRTUAL);
		super(parent, style);
		this.tablename = tablename;
		this.createContent();
	}
//	public WTable(Composite parent, int style, String tablename, IBaseService<? extends BaseModel<?>> service) {
//		//super(parent, style | SWT.VIRTUAL);
//		super(parent, style);
//		this.tablename = tablename;
//		this.service = service;
//		this.createContent();
//	}
//	public WTable(Composite parent, int style, String tablename, IBaseService<? extends BaseModel<?>> service) {
//		// super(parent, style | SWT.VIRTUAL);
//		super(parent, style);
//		this.tablename = tablename;
//		this.service = service;
//		this.dicService = dicService;
//		this.createContent();
//	}
	public WTable(Composite parent, int style) {
		//super(parent, style | SWT.VIRTUAL);
		super(parent, style);
		this.createContent();
	}
	public WTable(Composite parent, int style, int x, int y, int width, int height) {
		this(parent, style);
		this.setBounds(x, y, width, height);
		
	}
	public WTable(Composite parent, int x, int y, int width, int height) {
		this(parent, SWT.NONE, x, y, width, height);
	}
	
	private void createContent() {
		self = this;
		
		this.setFont(Const.getDefaultFont());
		setHeaderVisible(true);
		setLinesVisible(true);
		
		WMenu menu = new WMenu(this);
		//mainTable.setMenu(menu);
		WMenuItem mntWidth = new WMenuItem(menu, SWT.CASCADE, "列设置", null);
		WMenu mnuWidth = new WMenu(mntWidth);
		mntWidth.setMenu(mnuWidth);
		
		WMenuItem mi = new WMenuItem(mnuWidth, SWT.PUSH, "自动列宽", new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				TableColumn[] cols = self.getColumns();
				if(cols != null) {
					for(TableColumn c : cols) {
						String classname = self.getShell().getClass().getName();
						if(WTableColumn.class.isInstance(c)) {
							WTableColumn wc = (WTableColumn)c;
							if(wc.getXField() != null){
								SysTableCol tc = tableColService.find(classname, self.tablename, wc.getXField());
								if(tc != null && tc.getXWidth() > 0 && tc.getXIsShow())
									c.pack();
							}
						}
					}
				}
			}
		});
		mi = new WMenuItem(mnuWidth, SWT.PUSH, "平均列宽", new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				int width = self.getSize().x;
				//int cnt = self.getColumnCount();
				int cnt = 0;
				if(self.getColumnCount() > 0) {
					for(TableColumn c : self.getColumns()) {
						if(c.getWidth() > 0) {
							cnt++;
						}
					}
				}
				if(cnt > 0) {
					int w = width / cnt;
					TableColumn[] cols = self.getColumns();
					if(cols != null) {
						for(TableColumn c : cols) {
							String classname = self.getShell().getClass().getName();
							if(WTableColumn.class.isInstance(c)) {
								WTableColumn wc = (WTableColumn)c;
								if(wc.getXField() != null){
									SysTableCol tc = tableColService.find(classname, self.tablename, wc.getXField());
									if(tc != null && tc.getXWidth() > 0 && tc.getXIsShow())
										c.setWidth(w);
								}
							}
						}
					}
				}
			}
		});
		mi = new WMenuItem(mnuWidth, SWT.PUSH, "恢复默认", new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				int cnt = self.getColumnCount();
				if(cnt > 0) {
					TableColumn[] cols =  self.getColumns();
					if(cols != null) {
						for(TableColumn c : cols) {
							//c.setWidth(c.defaultWidth());
							((WTableColumn)c).setDefaultWidth();
						}
					}
				}
			}
		});
		mi = new WMenuItem(mnuWidth, SWT.PUSH, "列设置", new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				//Msg.show(self.getShell(), "错误", "未实现功能");
				String classname = self.getShell().getClass().getName();
				if(classname != null && self.tablename != null) {
					// new WTableSettingShell(classname, self.tablename, datas != null && datas.size() > 0 ? datas.get(0) : null).go();
					// TODO
					Msg.show(self.getShell(), "错误", "未实现功能");
				}
			}
		});
		mi = new WMenuItem(menu, SWT.PUSH, "TO EXCEL (UNFINISHED)", new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Msg.show(self.getShell(), "错误", "未实现功能");
			}
		});
//		if(self.service != null) {
//			mi = new WMenuItem(menu, SWT.PUSH, "删除", new SelectionAdapter() {
//				@Override
//				public void widgetSelected(SelectionEvent e) {
//					Msg.show(self.getShell(), "错误", "未实现功能");
////					if(self.service != null) {
////						int index = self.getSelectionIndex();
////						if(index >= 0) {
////							WTableItem item = (WTableItem)self.getItem(index);
////							Object m = item.getModel();
////							if(m != null && Msg.confirm(self.getShell(), "警告", "确定删除吗?注意,删除操作不可恢复", SWT.OK | SWT.CANCEL) == SWT.OK) {
////								if(service.delete(m)) {
////									Msg.show("操作结果", "删除成功,请刷新");
////								}else {
////									Msg.error(self.getShell(), "删除失败");
////								}
////							}
////						}
////					}else {
////						
////					}
//				}
//			});
//		}
	}
	
	@Override
	protected void checkSubclass() {}
	
	/**
	 * 取得控件右下角的定点的x
	 * @return
	 */
	public int getVertexX() {
		return this.getLocation().x + this.getSize().x;
	}
	/**
	 * 取得控件右下角的定点的y
	 * @return
	 */
	public int getVertexY() {
		return this.getLocation().y + this.getSize().y;
	}
	
	public void show(String tablename, String key, List<? extends IRow<? extends IRow<?>>> objs) {
		this.datas = objs;
		this.show(tablename, key);
	}
	
	/**
	 * 如果已经设置field,data则读取数据到表格
	 * @param key 搜索关键字
	 */
	@SuppressWarnings("unchecked")
	public void show(String tablename, String key) {
		if(datas != null) {	// field != null && 
			// 未建立列, 未建立列的话, 建立默认的列, 列出所有列
			// 需要再搞个窗口出来, 设置列的, 允许隐藏列以及修改列名
			// 如果还没有列
			if(this.getColumnCount() == 0) {
				// 但是有配置信息了
				// List<YTTableCol> cols = SQLite.getInstance().tablecolService.list(this.getShell().getClass().getName(), tablename);
				List<SysTableCol> cols = tableColService.list(this.getShell().getClass().getName(), tablename);
				if(cols != null && cols.size() > 0) {
					for(SysTableCol c : cols) {
						WTableColumn col = new WTableColumn(this, SWT.NONE, c.getXTitle(), tablename, c.getXField());
						col.setFormat(c.getXFormat()).setType(c.getXType());
					}
				}// 还没有配置, 就只能按字段名作为标题了
				else if(datas != null && datas.size() > 0 ) {		// && datas.get(0)._getAttrNames().length > 0
					// IRow<? extends IRow<?>> m = datas.get(0);
					var m = datas.get(0);
					Set<String> names = m.toMap().keySet();
					// String[] names = m._getAttrNames();
					for(String s : names) {
						WTableColumn col = new WTableColumn(this, SWT.NONE, s, tablename, s);
						if(SKIPFIELDS.contains(s)) {
							col.setWidth(0);
						}
					}
				}// 如果连1行数据都还没有呢? 这个怎么办? 这个没辙
				else {}
			}
			// 显示数据
			//long before = System.currentTimeMillis();
			this.removeAll();
//			List<YTTableColItem> tcitems = SQLite.getInstance().tablecolItemService.list(self.getShell().getClass().getName(), self.tablename);
//			Map<String, YTTableColItem> maps = new LinkedHashMap<>();
//			if(tcitems != null) {
//				for(YTTableColItem t : tcitems) {
//					maps.put(t.getStr("xField"), t);
//				}
//			}
			for(var m : datas) {		// IRow<? extends IRow<?>>
				int i = 0;
				boolean finded = false;
				TableColumn[] tcs = this.getColumns();
				String[] array = new String[tcs.length];
				if(tcs != null) {
					for(TableColumn t : tcs) {
						WTableColumn wc = (WTableColumn) t;
						String xField = wc.getXField();
						//YTTableColItem r;
//						if(xField.equals("rOwner_ID") 
//								|| xField.equals("rAuthor_ID")
//								|| xField.equals("rChecker_ID")
//								|| xField.equals("rMender_ID")
//								|| xField.equals("rAuditor_ID")) {
//							YTUser user = YTUser.getInstance(m.getInt(xField));
//							if(user != null)
//								array[i] = user.getXName();
//							else
//								array[i] = "[ERROR:查无此人]";
//						}else 
						if(self.dicService != null && xField.equals("rDic_ID")) {
							SysDic dic = self.dicService.find(m.getInt("rDic_ID"));
							if(dic != null) {
								array[i] = dic.getStr("xName");
							}else {
								array[i] = "";
							}
//						}else if(xField.equals("sStatus")) {
//							array[i] = Status.getInstance(m.getInt(xField)).getXName();
						//}else if((r = wc.getReplace(SQLite.getInstance().tablecolService.find(self.getShell().getClass().getName(), tablename, xField).getSID())) != null){
						}else if((wc.getType() == 3 || wc.getType() ==2 ) && wc.getFormat() != null && wc.getFormat().length() > 0) {
							boolean f = false;
							// 日期
							if(wc.getType() == 3) {
									array[i] = new SimpleDateFormat(wc.getFormat()).format(m.getTimestamp(xField));
							}else if (wc.getType() == 2){
								// 数值
								array[i] = new DecimalFormat(wc.getFormat()).format(m.getInt(xField));
							}
							f = true;
						}
//						else if(maps.get(xField) != null){
//							boolean f = false;
//							for(YTTableColItem tc : tcitems) {
//								if(xField.equals(tc.getStr("xField")) && m.getInt(xField).equals(tc.getInt("xValue"))) {
//									array[i] = tc.getStr("xName");
//									f = true;
//									break;
//								}
//							}
//							if(!f) {
//								array[i] = m.getStr(xField);
//							}
//						}
						else {
							array[i] = m.getStr(xField);
						}
						if(t.getWidth() > 0) {
							if(key == null || key.length() == 0 || (key.length() > 0 && m.getStr(xField) != null && m.getStr(xField).contains(key))) {
								finded = true;
							}
						}else {
						}
						i++;
					}
				}
				
				if(finded) {
					WTableItem item = new WTableItem(this, array);
					item.setModel((IRow<? extends IRow<?>>) m);
				}
			}
			if(this.isAutoPack) {
				for(TableColumn c : this.getColumns()) {
					String classname = self.getShell().getClass().getName();
					if(WTableColumn.class.isInstance(c)) {
						WTableColumn wc = (WTableColumn)c;
						// YTTableCol tc = SQLite.getInstance().tablecolService.find(classname, self.tablename, wc.getXField());
						SysTableCol tc = tableColService.find(classname, self.tablename, wc.getXField());
						if(tc != null && tc.getXWidth() > 0 && tc.getXIsShow())
							c.pack();
					}
				}
			}  
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public List<? extends IRow<?>> getDatas() {
		return datas;
	}
	public WTable setDatas(List<? extends IRow<?>> datas) {
		this.datas = datas;
		return this;
	}
	
	public String getTablename() {
		return tablename;
	}
	public WTable setTablename(String tablename) {
		this.tablename = tablename;
		return this;
	}
	public boolean getIsAutoPack() {
		return isAutoPack;
	}
	public WTable setIsAutoPack(boolean isAutoPack) {
		this.isAutoPack = isAutoPack;
		return this;
	}
	public int getType() {
		return type;
	}
	public WTable setType(int type) {
		this.type = type;
		return this;
	}
//	public IBaseService<? extends BaseModel<?>> getService() {
//		return service;
//	}
//	public WTable setService(IBaseService<? extends BaseModel<?>> service) {
//		this.service = service;
//		return this;
//	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

}
